const http = require('http')
const fs = require('fs');
const zlib = require('zlib')

let server = http.createServer((req,res)=>{
    res.on('finish',()=>{
        console.log('传输结束')
    })

    fs.stat(`www${req.url}`,(err,stat)=>{
        if(err){
            res.writeHeader(404);
            res.write("Not Found");
            res.end();
        }else{
            if(req.headers['if-modified-since']){
                let c_time = new Date(req.headers['if-modified-since']);
                let c_time_stamp = Math.floor(c_time.getTime()/1000);
                let s_time_stamp = Math.floor(stat.mtime.getTime()/1000);
                if(s_time_stamp>c_time_stamp){
                    toSendFile();
                }else{
                    //不发送，使用浏览器本地缓存
                    res.writeHeader(304);
                    res.write("Not Modified");
                    res.end();
                }
            }else{
                toSendFile();
            }
            
        }
        //发送源文件
        function toSendFile(){
            let rs = fs.createReadStream(`www${req.url}`);
            rs.on('error',err=>{
                res.writeHead(404)
                res.write('Not Found')
                res.end()
            })
            res.setHeader("Content-Encoding","gzip")
            res.setHeader("Last-Modified",stat.mtime.toUTCString())
            let gz = zlib.createGzip()
            rs.pipe(gz).pipe(res)
        }
    })
    

    
})

server.listen(8080)